package com.ruoyi.common.utils.kimi;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

/**
 * 调用 Kimi 大模型 API，根据姓名+职业返回生日
 * 运行方式：java KimiStarBirthday <姓名> [职业]
 */
public class KimiStarBirthday {

    private static final String API_KEY = "sk-AuIln00pDR1MNzqvctorJBBLGHgPNmz5NWxO3yd6BP7CVeBQ";
    private static final String URL    = "https://api.moonshot.cn/v1/chat/completions";

    public static void main(String[] args) throws IOException {
        String name="易嘉爱";
        String job="中国女歌手，SNH48成员";
        String birthday = queryBirthday(name, job);
        System.out.println(name + " 的生日是：" + birthday);
    }

    public static String queryBirthday(String name, String job) throws IOException {
        String body = "{\n" +
                "  \"model\": \"kimi-k2-0711-preview\",\n" +
                "  \"messages\": [\n" +
                "    {\"role\": \"user\", \"content\": \"请只告诉我" + job + "“" + name + "”的生日，格式为 YYYY-MM-DD，不要多余解释。\"}\n" +
                "  ],\n" +
                "  \"temperature\": 0.6,\n" +
                "  \"max_tokens\": 65536\n" +
                "}";

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.getBytes(StandardCharsets.UTF_8));
        }

        StringBuilder resp = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                resp.append(line);
            }
        }

        return resp.toString()
                .replaceAll(".*\"content\"\\s*:\\s*\"(\\d{4}-\\d{2}-\\d{2})\".*", "$1");
    }
}
